 <template>
  <div class="center">
    <el-form :model="form" :rules="rules" ref="formRef">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input-number v-model="form.age" controls-position="right" :min="0" :max="150" placeholder="请输入年龄"></el-input-number>
      </el-form-item>
      <el-form-item label="是否学生" prop="isStudent">
        <el-switch v-model="form.isStudent"></el-switch>
        </el-form-item>
      <el-form-item label="余额" prop="money">
        <el-input v-model="form.money" placeholder="0" disabled></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确认</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { userInfo } from '../api/login'
import { submitForm } from '../api/myInformation'

const formRef = ref(null);
const form = ref({
  name: '',
  age: null,
  isStudent: false,
});

const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'change' },
  ],
};
onMounted(() => {
  userInfo(localStorage.getItem('userAccount') ).then(res => {
          form.value=res.data
          form.value.isStudent=res.data.isStudent===1?true:false
        }
        ).catch(err => {
          console.log(err)
        })
});

const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 提交表单逻辑
      submitForm({id: localStorage.getItem('userId'),name:form.value.name,age:form.value.age,isStudent:form.value.isStudent?1:0}).then(res => {
        alert('提交成功');
        }
        ).catch(err => {
          alert('请检查表单!');
        })
    } else {
      alert('请检查表单');
    }
  });
};

const onCancel = () => {
  // 重置表单逻辑
  userInfo(localStorage.getItem('userAccount') ).then(res => {
          form.value=res.data
        }
        ).catch(err => {
          console.log(err)
        })
};

</script>

<style>
.center {
  border: 1px solid #ccc; /* 边框样式，颜色和宽度可自定义 */
  padding: 20px; /* 内边距，可以使内容与边框之间有空隙 */
  box-sizing: border-box; /* 确保padding和border不会增加元素的总宽度和高度 */
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%; /* 或者你想要的高度 */
}
</style>